package com.example.base.job;

import com.example.base.app.AppClassService;
import com.example.base.utils.ReflectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class JobAppMap {

    private Map<String, Set<IJob>> appJobMap;

    @Autowired
    private AppClassService appClassService;

    public void add(String appName,IJob job){
        if(appJobMap==null){
            appJobMap=new ConcurrentHashMap<>();
        }
        Set<IJob> appJob = appJobMap.computeIfAbsent(appName, k -> new HashSet<>());
        IJob iJob=appJob.stream().filter(e->e.getClass().getName().equals(job.getClass().getName())).findFirst().orElse(null);
        if(iJob==null){
            appJob.add(job);
        }
    }

    public IJob getIJob(String appName,String appClass){
        List<IJob> iJobList=getIJobList(appName);
        return iJobList.stream().filter(e->e.getClass().getName().equals(appClass)).findFirst().orElse(null);
    }

    public List<IJob> getIJobList(String appName){
        Set<IJob> iJobs=appJobMap.get(appName);
        List<IJob> iJobList=new ArrayList<>();
        if(iJobs!=null){
            iJobList.addAll(iJobs);
        }
        return iJobList;
    }

    public void clear(String appName){
        if(appJobMap!=null){
            Set<IJob> jobSet=appJobMap.get(appName);
            appJobMap.remove(appName,jobSet);
        }
    }

    public Set<Class<?>> getAppJobClass(String appName){
       List<Class<?>> classList=appClassService.getClassByAppName(appName);
       Set<Class<?>> classSet=new HashSet<>();
        for (int i = 0; i < classList.size() ; i++) {
            Class<?> cls=classList.get(i);
            Boolean isJob=ReflectUtils.isClassImplementedInterface(cls,IJob.class);
            if(isJob){
                classSet.add(cls);
            }
        }
        return classSet;
    }


}
